package com.itjiange.servlet;

import com.itjiange.constant.UserStatus;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;
import java.util.Set;

/**
 * 在线人数
 */
@WebServlet("/online")
public class OnlineServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取登录用户的数量 --> ServletContext 中的值
        ServletContext servletContext = req.getServletContext();
        Map<String, HttpSession> sessionMap = (Map<String, HttpSession>) servletContext.getAttribute(UserStatus.LOGIN_ING);
        resp.setContentType("text/html;charset=utf-8");
        StringBuilder html = new StringBuilder("<h2>在线人数" + sessionMap.size() + "</h2>");
        Set<Map.Entry<String, HttpSession>> sessionEntries = sessionMap.entrySet();
        for (Map.Entry<String, HttpSession> sessionEntry : sessionEntries) {
            html.append("<p>")
                    .append(sessionEntry.getValue().getId())
                    .append("  ")
                    .append(sessionEntry.getValue().getAttribute(UserStatus.USER_LOGIN_ING))
                    .append("<a href='/outline'>")
                    .append("下线")
                    .append("</a>")
                    .append("</p>");
        }
        resp.getWriter().write(html.toString());

    }
}